﻿using System;
using System.Collections;
using System.Data;
using System.Text;

namespace Coffee.Lists
{
    public class cls_Formula
    {
        private TSoft.Data.DataLayer DBLayer;

        public int ProductID { get; set; }
        public string Notes { get; set; }

        public cls_Formula()
        {
            DBLayer = new TSoft.Data.DataLayer();
        }

        public DataTable GetAll()
        {
            return DBLayer.ExecDataTable("sp_Lst_Formula", "Command", "GetAll");
        }

        public DataTable GetDetail(int v_MasterID)
        {
            return DBLayer.ExecDataTable("sp_Lst_Formula_Detail", "Command,MasterID", "GetAllByMasterID", v_MasterID);
        }

        public void Update(System.Data.DataTable Data)
        {
            try
            {
                if (ProductID == 0)
                    throw new Exception("Không tìm thấy sản phẩm cần tạo lập công thức.");

                DBLayer.BeginTransaction();

                DBLayer.ExecDataTable("sp_Lst_Formula", "Command,ProductID,Notes", "Update", ProductID, Notes);

                DBLayer.ExecDataTable("sp_Lst_Formula_Detail", "Command,MasterID", "DeleteAllByMasterID", ProductID);
                foreach (DataRow row in Data.Rows)
                {
                    DBLayer.ExecNonQuery("sp_Lst_Formula_Detail", "Command,MasterID,ProductID,Quantity,UnitID", "Update",
                            ProductID, TSoft.Cvert.ToInt32(row["ProductID"], 0),
                            TSoft.Cvert.ToDecimal(row["Quantity"], 0), TSoft.Cvert.ToInt32(row["UnitID"], 0));
                }

                DBLayer.CommitTransaction();
            }
            catch (Exception ex)
            {
                DBLayer.RollbackTransaction();
                throw ex;
            }
        }

        public void OnDelete()
        {
            DBLayer.ExecNonQuery("sp_Lst_Formula", "Command,ProductID", "Delete", ProductID);
        }
    }
}
